﻿using System.Configuration;
using System.Xml;

namespace Cache.Redis
{
    public class RedisSection
    {
        public static RedisConfig GetConfig()
        {
            var section = ConfigurationManager.GetSection("Cache") as XmlNode;

            foreach (XmlNode child in section.ChildNodes)
            {
                if (child.Name.ToLower() == "redis")
                {
                    //Console.WriteLine(section.InnerXml.ToString());
                    return ParseConfig(child);
                }
            }
            return null;
        }

        private static RedisConfig ParseConfig(XmlNode section)
        {
            var config = new RedisConfig();
            foreach (XmlNode child in section.ChildNodes)
            {
                if (child.Name.ToLower() == "setting")
                {
                    if (child.Attributes["IsCache"] != null)
                    {
                        config.IsCache = bool.Parse(child.Attributes["IsCache"].Value);
                    }
                    if (child.Attributes["SendTimeout"] != null)
                    {
                        config.SendTimeout = int.Parse(child.Attributes["SendTimeout"].Value);
                    }
                }
                else if (child.Name.ToLower() == "add")
                {
                    var node = new RedisNode();
                    if (child.Attributes["name"] != null)
                    {
                        node.Name = child.Attributes["name"].Value;
                    }
                    if (child.Attributes["Host"] != null)
                    {
                        node.Host = child.Attributes["Host"].Value;
                    }
                    if (child.Attributes["Port"] != null)
                    {
                        node.Port = int.Parse(child.Attributes["Port"].Value);
                    }
                    if (child.Attributes["PassWord"] != null)
                    {
                        node.PassWord = child.Attributes["PassWord"].Value;
                    }
                    if (child.Attributes["DefaultDB"] != null)
                    {
                        node.DefaultDB = int.Parse(child.Attributes["DefaultDB"].Value);
                    }
                    config.Nodes.Add(node.Name, node);
                }
            }
            return config;
        }
    }
}